<template>
  <div class="app-container">
    <div class="app-container-header">
      <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" label-width="80px">
        <el-form-item label="设备名称" prop="monitorName">
          <el-input
            v-model="queryParams.monitorName"
            placeholder="请输入设备名称"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
    <el-row style='margin-bottom: 10px;'>
      <!-- <div class="app-container-header-end"> -->
        <el-button type="primary" icon="el-icon-plus" size="mini" @click="handleAdd">新增</el-button>
        <el-button type="primary" icon="el-icon-refresh-right" size="mini" @click="refresh">更新</el-button>
      <!-- </div> -->
    </el-row>

    <div class="app-container-main">
      <el-table v-loading="loading" :data="planList">
        <el-table-column align="center" class-name="small-padding fixed-width" width="40">
          <template slot-scope="scope">
            <el-button
              type="text"
              icon="el-icon-link"
              @click="toDetail(scope.row)"
            ></el-button>
          </template>
        </el-table-column>
        <el-table-column label="设备名称" align="center" prop="monitorName" />
        <el-table-column label="类路径" align="center" prop="address" />
        <el-table-column label="创建时间" align="center" prop="createTime" />
        <el-table-column label="设备类型" align="center" prop="monitorType" />
        <el-table-column label="轮询" align="center" prop="cycle" >
          <template slot-scope="scope">
            <span>{{ scope.row.cycle + 'ms' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="启用" align="center" prop="enabled" >
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.enabled"
              disabled
              active-color="#13ce66"
              inactive-color="#ff4949">
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column label="模型地址" align="center" prop="modelUrl" />
        <el-table-column label="模型缩略图" align="center" prop="modelImageUrl" >
          <template slot-scope="scope">
            <el-image
              style="width: 100px; height: 100px"
              :src="scope.row.modelImageUrl"
              fit="cover">
            </el-image>
          </template>
        </el-table-column>
        <el-table-column label="备注" align="center" prop="remark" />
        <el-table-column label="状态" align="center" prop="status" >
          <template slot-scope="scope">
            <el-tag :type="scope.row.status === 'ok' ? 'success' : 'danger'">{{scope.row.status === 'ok' ? '正常' : '异常'}}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              icon="el-icon-edit"
              @click="handleUpdate(scope.row)"
            >修改</el-button>
            <el-button
              size="mini"
              type="text"
              icon="el-icon-delete"
              @click="handleDelete(scope.row)"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-show="total>0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
      />
    </div>
    <el-dialog :title="title" :close-on-click-modal="false" :visible.sync="open" width="600px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="设备名称" prop="monitorName">
          <el-input v-model="form.monitorName" placeholder="请输入设备名称" />
        </el-form-item>
        <el-form-item label="关联设备" prop="machineryId">
          <el-select v-model="form.machineryId" placeholder="请选择关联设备">
            <el-option
              v-for="dict in deviceList" 
              :key="dict.machineryId"
              :label="dict.machineryName"
              :value="dict.machineryId"
              />
          </el-select>
        </el-form-item>
        <el-row>
          <el-col :span="11">
            <el-form-item label="协议类型" prop="monitorType">
              <el-select v-model="form.monitorType" placeholder="请选择协议类型">
                <el-option
                  v-for="dict in dict.type.dv_agreement_type" 
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                  />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="轮询" prop="cycle" label-width="60px">
              <el-select v-model="form.cycle" placeholder="请选择时长">
                <el-option
                  v-for="dict in dict.type.mes_communication_cycle" 
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                  />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="5">
            <el-form-item label="启用" prop="enabled" label-width="60px">
              <el-switch
                v-model="form.enabled"
                active-color="#13ce66"
              >
              </el-switch>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="地址" prop="address">
          <el-input v-model="form.address" placeholder="请输入地址" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="缩略图" prop="modelImageUrl">
          <ImageUpload v-model="form.modelImageUrl" :limit="1" @onUploaded="onUploaded" />
        </el-form-item>
        <el-form-item label="3D模型" prop="modelUrl">
          <modelUpload v-model="form.modelUrl" @input="onModelUpload" :fileType="fileType" :fileSize="20" :limit="1" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm" >确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listMnitor,
  getMnitorDeviceInfo,
  getBrowerNodes,
  addMnitor,
  putMnitor,
  delMnitor,
} from "@/api/mes/dv/communication";
import { listMachinery } from "@/api/mes/dv/machinery";
import modelUpload from "@/components/modelUpload";
export default {
  name: 'Communication',
  dicts: ['mes_communication_cycle', 'dv_agreement_type'],
  components: {
    modelUpload
  },
  data(){
    return{
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 总条数
      total: 0,
      // 生产计划表格数据
      planList: [],
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        monitorName: null,
      },
      // 弹出层标题
      title: "",
      open: false,
      // 查询参数
      form: {
        enabled: false,
        monitorType: 'Opc UA',
        status: 'ok',
      },
      // 表单校验
      rules: {
        monitorName:[{
          required: true,
          message: "监测点名称不能为空",
          trigger: "blur"
        }],
        monitorType:[{
          required: true,
          message: "监测点类型不能为空",
          trigger: "change"
        }],
        cycle:[{
          required: true,
          message: "监测周期不能为空",
          trigger: "change"
        }],
        address:[{
          required: true,
          message: "监测周期不能为空",
          trigger: "blur"
        }],
        machineryId:[{
          required: true,
          message: "设备不能为空",
          trigger: "change"
        }]
      },
      fileType:['gltf', 'glb',], // 暂定只支持gltf和glb格式
      // 'gltf', 'glb', 'stl', 'fbx','obj','3dm','3mf','3ds', 
      // 'amf','dae','wrl','ply','vtk','vtp','stp','step','xyz','ifc',
      // 'dxf','dwg','rvt','rvm','dgn','usd','usdz','usda','usdc'
      deviceList: [],
    }
  },
  created() {
    this.getList();
  },
  methods:{
    getDeviceList(){
      listMachinery({pageNum: 1, pageSize: 9999}).then(res => {
        this.deviceList = res.rows;
      }).catch(err => {
        console.log(err);
      })
    },
    async getList(){
      const res = await listMnitor(this.queryParams);
      this.planList = res.rows;
      this.total = res.total;
      this.loading = false;
    },
    handleQuery(){
      this.getList()
    },
    resetQuery(){
      this.resetForm("queryForm");
      this.handleQuery();
    },
    refresh(){
      this.getList();
      // console.log('refresh');
    },
    handleAdd(){
      this.open = true;
      this.title = "添加设备";
      this.getDeviceList()
    },
    handleUpdate(row){
      this.open = true;
      this.title = "修改设备";
      this.getDeviceList()
      this.form = {...row};
      console.log(this.form);
    },
    handleDelete(row){
      this.$confirm('是否确认删除名称为"' + row.monitorName + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delMnitor(row.deviceMonitorId);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        })
    },
    toDetail(row){
      this.$router.push({
        path:'/mes/dv/communication/detail',
        query:{
          id: row.deviceMonitorId,
          cycle: row.cycle,
          enabled: row.enabled,
        }
      })
    },
    cancel(){
      this.open = false;
      this.resetForm('form')
    },
    resetForm(form){
      this.$refs[form].resetFields();
      this.form = {
        enabled: false,
        monitorType: 'Opc UA',
        status: 'ok',
      }
    },
    submitForm(){
      this.$refs["form"].validate(valid => {
        if (valid) {
          console.log(this.form);
          if (this.form.deviceMonitorId != null) {
            putMnitor(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.cancel();
              this.getList();
            });
          } else {
            addMnitor(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.cancel();
              this.getList();
            });
          }
          // this.resetQuery()
        }
      });
    },
    // 上传缩略图
    onUploaded(file){
      console.log(file);
      this.form.modelImageUrl = file;
    },
    // 上传模型
    onModelUpload(file){
      // console.log(file);
      this.form.modelUrl = file;
    },
  }
}
</script>

<style lang="scss" scoped>
.app-container {
  background-color: #fff;
  padding: 10px;
  &-header{
    display: flex;
    justify-content: space-between;
  }
}
</style>